package com.probiz.estoresa.sales.web.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.servlet.ModelAndView;

import com.probiz.estore.catalog.service.GiftCategoryManager;
import com.probiz.estore.common.helper.ConfigUtil;
import com.probiz.estore.common.model.catalog.GiftCategory;
import com.probiz.estore.common.model.sales.Gift;
import com.probiz.estore.core.controller.GenericStoreAdminController;
import com.probiz.estore.core.exception.ApplicationException;
import com.probiz.estore.core.search.SearchCriteria;
import com.probiz.estore.customer.service.MembershipManager;
import com.probiz.estore.sales.model.GiftFullyModel;
import com.probiz.estore.sales.model.GiftSearchCriteria;
import com.probiz.estore.sales.service.GiftManager;
import com.probiz.estore.webapp.util.RequestUtil;

public class GiftController extends GenericStoreAdminController<Gift> {
    private GiftManager giftManager = null;
	private GiftCategoryManager	giftCategoryManager	= null;
	private MembershipManager	membershipManager;

	public void setGiftCategoryManager(GiftCategoryManager giftCategoryManager) {
		this.giftCategoryManager = giftCategoryManager;
	}

	public void setGiftManager(GiftManager inMgr) {
		this.giftManager = inMgr;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.GenericStoreAdminController#getEntityName(java.lang.Object)
	 */
	@Override
	protected String getEntityName(Gift entity) {
		return entity.getGiftName();
	}


	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.GenericStoreAdminController#initController()
	 */
	@Override
	protected void initController() throws Exception {
		mgr = giftManager;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.probiz.estore.core.controller.GenericStoreAdminController#preSave(javax.servlet.http.HttpServletRequest,
	 *      java.lang.Object, org.springframework.validation.BindException)
	 */
	@Override
	protected void preSave(HttpServletRequest request, Gift entity,
			BindException errors) {
	}

	public ModelAndView defaultAction(HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("sales/giftList");
		GiftCategory treeRoot = giftCategoryManager.getById(1);
		Set<GiftCategory> categorySet = treeRoot.getChildren();
		List<GiftCategory> categoryList = new ArrayList<GiftCategory>();
		categoryList.addAll(categorySet);
		mv.addObject("categoryList", categoryList);
		mv.addObject("treeRoot", treeRoot);

		return mv;
	}

	/**
	 * 加载图片区域
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView loadAreaOfImages(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView("sales/include/giftFormImages");
		Gift gift = formBackingObject(request);
		mv.addObject("gift", gift);
		return mv;
	}

	/**
	 * 重载add方法，主要是去掉设置导航信息,否则列表页面跳转会有问题，（savedNavAndSearchCriteria(....)），其他处理与框架一致，
	 */
	public ModelAndView add(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView(formView);
		Gift gift = formBackingObject(request);

		// start:礼品目录
		if (StringUtils.isNotBlank(RequestUtil.getParameterNullSafe(request,
				"giftCategoryId"))) {
			gift.setCategory(giftCategoryManager.getById(Integer
					.valueOf(RequestUtil.getParameterNullSafe(request,
							"giftCategoryId"))));
		}
		// end:礼品目录
//		List<Membership> membershipList = membershipManager
//				.getAllMembershipsOrderByLevel(StoreUtil.getCurrentStoreId(request), true);
//		mv.addObject("membershipList", membershipList);

		mv.addObject("gift", gift);
		mv.addObject("weightUnit", ConfigUtil.getInstance().getWeightUnit());

		return mv;
	}

	public ModelAndView search(HttpServletRequest request,
			HttpServletResponse response) {
		ModelAndView mv = new ModelAndView("sales/include/giftListBody");
		SearchCriteria searchCriteria = createSearchCriteria(request);
		GiftSearchCriteria giftSearchCriteria = new GiftSearchCriteria();
		try {
			// 绑定参数
			bind(request, giftSearchCriteria);
			List<Gift> giftList = giftManager.searchByCriteriaForController(
					giftSearchCriteria, searchCriteria);
			mv.addObject("giftList", giftList);
			mv.addObject("giftSearchCriteria", giftSearchCriteria);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return mv;
	}

	public ModelAndView save(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// 取得Form对应的Model
		Gift entity = formBackingObject(request);
		BindException errors = null;
		Map<String, Object> data = new HashMap<String, Object>();
		try {
			bindReady(entity);
			ServletRequestDataBinder binder = bindAndValidate(request, entity);
			errors = new BindException(binder.getBindingResult());
			// 传给子类的实现，后者可以继续验证和加入错误到errors
			preSave(request, entity, errors);
			if (!errors.hasErrors()) {// 里面如果出错应该抛出异常
				GiftFullyModel giftFullyModel = getGiftFullyModel(request,
						entity, data);
				Map<String, Object> saveData = giftManager
						.saveFully(giftFullyModel);
				data.putAll(saveData);
			}
		} catch (ApplicationException e) {
			handleApplicationException(errors, e);
		}

		buildReturnInfo(data, entity, request);

		return getModelAndAjaxJsonView(data);
	}

	// 加入返回参数
	private void buildReturnInfo(Map<String, Object> data, Gift gift,
			HttpServletRequest request) {
		data.put("giftId", gift.getGiftId());
		data.put("giftName", gift.getGiftName());
		data.put("giftCode", gift.getGiftCode());
		data.put("status", gift.getStatus());

	}

	// 保存前的绑定
	private void bindReady(Gift entity) {
		if (null == entity.getGiftId()) {
			// case:新增
			
		}

	}

	// 构造礼品模型，方便保存
	private GiftFullyModel getGiftFullyModel(HttpServletRequest request,
			Gift gift, Map<String, Object> data) {
		GiftFullyModel model = new GiftFullyModel();
		model.setGift(gift);

		return model;

	}

	/**
	 * 根据目录id获得路径全名
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView getFullCategoryPathName(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		Map<String, Object> data = new HashMap<String, Object>();
		GiftCategory giftCategory = giftCategoryManager.getById(RequestUtil
				.getInteger(request, "categoryId"));
		data
				.put("fullCategoryPathName", giftCategory
						.getFullCategoryPathName());
		return getModelAndAjaxJsonView(data);
	}

	public ModelAndView multiDelete(HttpServletRequest request,
			HttpServletResponse response) {
		// 取得要删除的记录的id的列表。注意：选择框的id要是"multiIds"。
		String[] ids = request.getParameterValues("multiIds");
		Map<String, Object> data = new HashMap<String, Object>();
		JSONArray jsonArray = new JSONArray();

		if (ids != null && ids.length > 0) {
			for (String entityId : ids) {
				Gift gift = giftManager.getById(Integer.valueOf(entityId));
				short deleteStatus = giftManager.deleteFully(gift);
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("giftName", gift.getGiftName());
				jsonObject.put("deleteStatus", deleteStatus);
				jsonArray.add(jsonObject);
			}
		}
		data.put("deleteInfos", jsonArray);
		JSONObject jsonMap = JSONObject.fromObject(data);
		PrintWriter out;
		try {
			out = response.getWriter();
			out.println(jsonMap.toString());
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public ModelAndView delete(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String entityId = request.getParameter(entityIdName);
		Gift gift = giftManager.getById(Integer.valueOf(entityId));
		short deleteStatus = giftManager.deleteFully(gift);

		Map<String, Object> data = new HashMap<String, Object>();
		JSONArray jsonArray = new JSONArray();
		JSONObject jsonObject = new JSONObject();
		jsonObject.put("giftName", gift.getGiftName());
		jsonObject.put("deleteStatus", deleteStatus);
		jsonArray.add(jsonObject);
		data.put("deleteInfos", jsonArray);
		JSONObject jsonMap = JSONObject.fromObject(data);
		PrintWriter out = response.getWriter();
		out.println(jsonMap.toString());
		return null;
	}

	/**
	 * 重载edit方法，主要是去掉设置导航信息,否则列表页面跳转会有问题，（savedNavAndSearchCriteria(....)），其他处理与框架一致，
	 */
	@Override
	public ModelAndView edit(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ModelAndView mv = new ModelAndView(formView);
		Gift gift = formBackingObject(request);

		// start:礼品目录
		if (StringUtils.isNotBlank(RequestUtil.getParameterNullSafe(request,
				"giftCategoryId"))) {
			gift.setCategory(giftCategoryManager.getById(Integer
					.valueOf(RequestUtil.getParameterNullSafe(request,
							"giftCategoryId"))));
		}
//		// end:礼品目录
//		List<Membership> membershipList = membershipManager
//				.getAllMembershipsOrderByLevel(gift.getStoreId(), true);
//		mv.addObject("membershipList", membershipList);

		mv.addObject("gift", gift);
		mv.addObject("weightUnit", ConfigUtil.getInstance().getWeightUnit());
		return mv;
	}

	public void setMembershipManager(MembershipManager membershipManager) {
		this.membershipManager = membershipManager;
	}
}
